import 'dart:developer';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

/// 标准的DataTable 示例
buildSampleDT() {
  return Container(
    child: DataTable(
      // DataTable 的列
      columns: [
        DataColumn(label: Text("姓名")),
        DataColumn(label: Text("年龄")),
      ],
      rows: [
        // DataTable 的每一行数据
        DataRow(cells: [
          DataCell(Text("老梦")),
          DataCell(Text("19")),
        ]),
        DataRow(cells: [
          DataCell(Text("老九")),
          DataCell(Text("21")),
        ]),
        DataRow(cells: [
          DataCell(Text("西门官人")),
          DataCell(Text("33")),
        ]),
      ],
    ),
  );
}

/// 高级定制的DataTable
buildSampleDT2() {
  return Container(
    child: DataTable(
      // 表示表格显示排序图标的索引
      // 要设置选择之后才生效
      sortColumnIndex: 1,
      // 表示升序或者降序
      // 要设置选择之后才生
      sortAscending: false,
      columnSpacing: 30.0,
      onSelectAll: (selectAll) {
        // 全部选中
        log("全选");
      },
      // 设置列宽
      columns: [
        DataColumn(label: Text("姓名"), tooltip: '长按提示'),
        DataColumn(
            label: Text("年龄"),
            // 右对齐
            numeric: true,
            onSort: (index, ascending) {
              // index 索引 , ascending 升序或降序
              log("index = $index , ascending = $ascending");
            }), // 让该列右对齐
      ],
      rows: [
        DataRow(cells: [
          DataCell(Text("老梦")),
          DataCell(Text("19")),
        ]),
        DataRow(
            // 设置选中
            selected: true,
            // 选择回调
            onSelectChanged: (selected) {
              log("点击了: selected = $selected");
            },
            cells: [
              DataCell(Text("老九")),
              DataCell(Text("75")),
            ]),
        DataRow(cells: [
          DataCell(Text("西门官人")),
          DataCell(Text("33")),
        ])
      ],
    ),
  );
}

/// 学生表
buildStudentList() {
  return StudentListWidget();
}

/// 学生数据表
class StudentListWidget extends StatefulWidget {
  const StudentListWidget({Key? key}) : super(key: key);

  @override
  _StudentListWidgetState createState() => _StudentListWidgetState();
}

class _StudentListWidgetState extends State<StudentListWidget> {
  List<User> dataList = [
    User("老孟", 18),
    User("小龙", 22, selected: true),
    User("老九", 15),
    User("西门官人", 21),
    User("西风", 34),
    User("老孟-2", 23),
    User("老孟-3", 37),
    User("老孟-4", 45),
    User("老孟-5", 43),
    User("老孟-6", 41),
    User("老孟-7", 28),
  ];

  // 排序
  var _sortAscending = true;
  var _sortColumnIndex = 1;

  @override
  Widget build(BuildContext context) {
    // return Container(
    //   child: buildDefaultDataTable(),
    // );

    return Container(
      // 解决数据列过多，数据显示不全的问题，支持横向滚动
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: buildDefaultDataTable(),
      ),
    );
  }

  DataTable buildDefaultDataTable() {
    return DataTable(
      sortAscending: _sortAscending,
      sortColumnIndex: _sortColumnIndex,
      // 控制需要排序的列
      columns: [
        DataColumn(
          label: Text("姓名"),
          //   onSort: (index, ascending) {
          //     setState(() {
          //       _sortAscending = ascending;
          //       if (ascending) {
          //         dataList.sort((a, b) => a.name.compareTo(b.name));
          //       } else {
          //         dataList.sort((a, b) => b.name.compareTo(a.name));
          //       }
          //     });
          //   },
          // ),
          onSort: sortByName,
        ),
        DataColumn(label: Text("年龄"), onSort: sortByAge),
        DataColumn(
            label: FlatButton(
          child: Text("全选/取消"),
          onPressed: () {
            setState(() {
              if (isAllSelect()) {
                log("取消全选");
                doUnSelect();
              } else {
                log("执行全选");
                doSelectAll();
              }
            });
          },
        )),
        DataColumn(label: Text("住址")),
        DataColumn(label: Text("Pid")),
        DataColumn(label: Text("性别")),
      ],
      rows: dataList.map((user) {
        return buildDataRow(user);
      }).toList(),
      // rows: buildTabRow(),
    );
  }

  buildTabRow() {
    List<DataRow> dataRows = <DataRow>[];
    for (int i = 0; i < dataList.length; i++) {
      var user = dataList[i];
      dataRows.add(buildDataRow(user));
    }
    return dataRows;
  }

  /// 构建行数据
  DataRow buildDataRow(User user) {
    return DataRow(
        selected: user.selected, // 设置选中
        onSelectChanged: (selected) {
          // 选中回调
          setState(() {
            user.selected = selected!; // 更新状态
          });
        },
        cells: [
          DataCell(Text("${user.name}")),
          DataCell(Container(
            alignment: Alignment.center,
            child: Text("${user.age}"),
          )),
          DataCell(Container(
            alignment: Alignment.center,
            child: IconButton(
              color: user.selected ? Colors.blue : Colors.grey, // 修改颜色
              icon: Icon(user.selected ? Icons.check_box : Icons.check_box_outline_blank),
              onPressed: () {},
            ),
          )),
          DataCell(Text("${user.address}")),
          DataCell(Container(
            alignment: Alignment.center,
            child: Text("${user.pid}"),
          )),
          DataCell(Container(
            alignment: Alignment.center,
            child: Text("${user.sex}"),
          ))
        ]);
  }

  /// 执行全选
  doSelectAll() {
    dataList.forEach((element) {
      element.selected = true;
    });
  }

  /// 执行全不选
  doUnSelect() {
    dataList.forEach((element) {
      element.selected = false;
    });
  }

  // 是否全选
  isAllSelect() {
    bool allSelect = true;
    dataList.forEach((element) {
      if (!element.selected) {
        allSelect = false;
      }
    });
    return allSelect;
  }

  /// 排序Name
  sortByName(int columnIndex, bool ascending) {
    log("sortByName columnIndex = $columnIndex , ascending = $ascending");
    // 处理排序
    setState(() {
      _sortAscending = ascending;
      // 排序
      if (ascending) {
        dataList.sort((a, b) => a.name.compareTo(b.name));
      } else {
        dataList.sort((a, b) => b.name.compareTo(a.name));
      }
    });
  }

  /// 排序Age
  sortByAge(int columnIndex, bool ascending) {
    log("sortByAge columnIndex = $columnIndex , ascending = $ascending");
    // 处理排序
    setState(() {
      _sortAscending = ascending;
      // 排序
      if (ascending) {
        dataList.sort((a, b) => a.age.compareTo(b.age));
      } else {
        dataList.sort((a, b) => b.age.compareTo(a.age));
      }
    });
  }
}

/// 用户
class User {
  String name;
  int age;
  bool selected;
  String address;
  String pid;
  String sex;

  User(this.name, this.age, {this.selected = false, this.address = "河北", this.sex = "男", this.pid = "050032"});
}
